package cn.tedu.search.service;

import com.alibaba.fastjson.JSONObject;
import com.easyhouse.common.pojo.Product;
import com.easyhouse.common.utils.MapperUtil;
import com.easyhouse.common.utils.StringConversionJavabeanUtils;
import com.easyhouse.common.vo.SysResult;
import com.fasterxml.jackson.core.JsonProcessingException;
import org.elasticsearch.action.admin.indices.delete.DeleteIndexResponse;
import org.elasticsearch.action.admin.indices.exists.indices.IndicesExistsResponse;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.delete.DeleteResponse;
import org.elasticsearch.action.get.GetRequestBuilder;
import org.elasticsearch.action.get.GetResponse;
import org.elasticsearch.action.index.IndexRequestBuilder;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchRequestBuilder;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.action.update.UpdateResponse;
import org.elasticsearch.client.IndicesAdminClient;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.transport.InetSocketTransportAddress;
import org.elasticsearch.common.unit.TimeValue;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.query.*;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.net.InetAddress;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

@Service
public class SearchServiceImpl implements SearchService{
    @Autowired
    private TransportClient client;
    public List<Product> search(String text, Integer page, Integer rows) {
        /*BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
        boolQueryBuilder.must(query1)*/
        //query对象封装
        MultiMatchQueryBuilder query1 = QueryBuilders.multiMatchQuery(text,"houseName","addrProvince","addrDistrict","houseAddr");

        //MatchQueryBuilder query = QueryBuilders.matchQuery("houseName", text);
        SearchRequestBuilder request = client.prepareSearch("easyhouse");
        int start = (page - 1) * rows;
        SearchResponse response =
                request.setQuery(query1)
                        .setFrom(start)
                        .setSize(rows).get();
        //准备一个封装号返回结果的list对象
        List<Product> products = new ArrayList<>();
        SearchHit[] hits = response.getHits().getHits();
        for (SearchHit hit : hits) {
            String json = hit.getSourceAsString();
            //转化成product对象
            try {
                Product product = MapperUtil.MP.readValue(json, Product.class);
                products.add(product);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        for (int i = 0; i < products.size(); i++) {
            System.out.println(products.get(i));
        }
        return products;
    }

    public void addingIndex(String productString) {
        //把string转换成Javabean
        Product product = StringConversionJavabeanUtils.StringJava(productString);
        //把json转成javabean
        //Product product = JSONObject.parseObject(productJson,Product.class);


        String indexName = "easyhouse";
        String type = "house";
            try {
                //Javabean转json
                String productJson = MapperUtil.MP.writeValueAsString(product);
                IndexRequestBuilder docRequest = client.prepareIndex(indexName, type, product.getHouseName());
                docRequest.setSource(productJson).get();
            } catch (Exception e) {
                e.printStackTrace();
        }
    }

    public void updateIndex(Product product) {
        //获取houseId
        String houseId = product.getHouseId();
        try {
            String productJson = MapperUtil.MP.writeValueAsString(product);
            client.prepareUpdate("easyhouse", "house", houseId)
                    .setDoc(productJson, XContentType.JSON).get();
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
    }
    public void deleteIndex() {
        client.admin().indices().prepareDelete("easyhouse").execute().actionGet();
    }

    @Override
    public void deleteIndexData(String houseId) {
        client.prepareDelete("easyhouse","house",houseId);
    }
}
